//使用命令进行安装：npm install crypto-js  --registry=https://registry.npmmirror.com
import CryptoJS from "crypto-js";
//调用的核心，使用webscoket技术
//身份信息
var appId = "2a072be1";
var appSecret = "YWJiOTkwZjU4YmEzYjg3MDE1Zjc2MTg0";
var apiKey = "e9ce17a66ef4dbc314b3106aee97acd8";
//1.创建websocket连接，连接到星火大模型
var url = "wss://spark-api.xf-yun.com/v3.5/chat";
var domain = "generalv3.5";
var version = "v3.5";
//.接口鉴权（目的：加密appSecret、apikey,学习：怎么利用大模型转换代码，接口鉴权流程）
var host = location.host
var date = new Date().toGMTString();
var get = `GET /${version}/chat HTTP/1.1`;
var tmp = `host: ${host}\ndate: ${date}\n${get}`;
//hmac-sha256算法加密
var tmp_sha256 = CryptoJS.HmacSHA256(tmp, appSecret);
//base64编码
var sign = CryptoJS.enc.Base64.stringify(tmp_sha256);
//对生成授权原始字符串进行拼接
var authorization_tmp = `api_key="${apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${sign}"`;
//对授权原始字符进行base编码
var authorization = btoa(authorization_tmp);
//最终url
url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
//2.发起Websocket
const createWss = (msg,dom) => {
  let wss = new WebSocket(url);

  wss.onopen = (e) => {
    console.log("websocket建立成功");
    sendMsg(msg,wss)
  };

  wss.onmessage = (e) => {
    let jsonData = JSON.parse(e.data)
    // 提问失败
    if (jsonData.header.code !== 0) {
      alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`)
      console.error(`${jsonData.header.code}:${jsonData.header.message}`)
    }
    //关闭webscoket
    if (jsonData.header.code === 0 && jsonData.header.status === 2) {
      wss.close()
    }
    //提问结果
    dom.innerText += jsonData.payload.choices.text[0].content
  };

  wss.onerror = (e) => {
    console.error(e);
  };

  wss.onclose = (e) => {
    console.log(e);
  };
};

const sendMsg = (msg,wss)=>{
  let data = {
    header:{
      app_id:appId
    },
    parameter:{
      chat:{
        domain:domain,
        temperature:0.5,
        max_tokens:1024
      }
    },
    payload:{
      message:{
        text:[
          {role:"user",content:msg}
        ]
      }
    }
  }
  wss.send(JSON.stringify(data))
}
//3.接收websocket的msg
//4.msg展示在页面


export default createWss
